package com.mf.ergate.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.Column;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * 反射工具类
 * User: zhaoming
 * Date: 13-5-9
 * Time: 下午5:01
 * To change this template use File | Settings | File Templates.
 */
public abstract class ReflectionUtils {

    private static final Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);

    /**
     * 自动填充唯一编号
     */
    public static void autoFillUniqueNo(Object entity){
        try {
            Field[] fields = entity.getClass().getDeclaredFields();
            for(Field field : fields){
                Column columnAnnotation = field.getAnnotation(Column.class);
                if(columnAnnotation != null && columnAnnotation.unique()){
                    field.setAccessible(true);
                    if(Objects.isNull(field.get(entity))){
                        field.set(entity, UUID.randomUUID().toString().replace("-", ""));
                    }
                }
            }
        } catch(Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * bean对象转Map
     * @param entity 实体对象
     * @return Map
     */
    public static Map<String, Object> beanToMap(Object entity) {
        Map<String, Object> map = new HashMap<>();
        if (entity == null) {
            return map;
        }
        Class clazz = entity.getClass();
        Field[] superClassFields = clazz.getSuperclass().getDeclaredFields();
        try {
            for (Field field : superClassFields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(entity));
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(entity));
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return map;
    }
}
